import sys
import json


def reformat_json_file(filename):
    try:
        # Read JSON file
        with open(filename, "r", encoding="utf-8") as f:
            data = json.load(f)

        # Write back to the same file with new formatting
        with open(filename, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, ensure_ascii=False)

        print(f"Successfully reformatted {filename}")

    except FileNotFoundError:
        print(f"Error: File '{filename}' not found")
    except json.JSONDecodeError:
        print(f"Error: Invalid JSON in file '{filename}'")
    except Exception as e:
        print(f"An unexpected error occurred: {str(e)}")


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python reformat_json.py <filename.json>")
        sys.exit(1)

    input_file = sys.argv[1]
    reformat_json_file(input_file)
